const exp = require("express")

const ejs = require("ejs")

const app = exp()

const userModel = require("./database/model/useModel")

app.set("views", __dirname + "/html")

app.engine("html", ejs.renderFile)

// 中间件
app.use(exp.urlencoded({ extended: false }))
// 路由

app.get("/", (req, res) => {
    userModel.find((err, data) => {
        if (err) return;
        // console.log(data);
        res.render("index.html", { data })
    })

})

app.get("/addUser", (req, res) => {
    res.render("addUser.html")
})

app.post("/addUser", (req, res) => {
    let { name, age } = req.body

    userModel.create({ name, age }, (err, data) => {
        if (!err) {
            res.send("添加成功")
        }


    })

})



app.get("/delete", (req, res) => {
    let _id = req.query
    userModel.deleteOne({ _id }, (err, data) => {
        if (!err) {
            res.send("删除成功")
        }
    })


})

app.get("/add", (req, res) => {
    let _id = req.query

    userModel.findById(_id, (err, data) => {


        if (!err) {
            res.render("add.html", { data })
        }
    })

})

app.post("/add/:_id", (req, res) => {

    let { _id } = req.params
    let { name, age } = req.body
    userModel.updateMany({ _id }, { name, age }, (err, data) => {
        if (!err) {
            res.send("修改成功")
        }

    })
})
app.listen(80, () => {
    console.log("成功 ");
})